<template>
    <div class="index">
        <div class="button-box">
            <el-button type="success" @click="gotoSend">发送消息</el-button>
        </div>
        
        <div class="inbox">
            <div class="inbox-container">
                <!-- 切换收发消息按钮 -->
                <div class="toggle-box" style="width:100%; display:flex; justify-content:flex-end; gap:8px; margin-bottom:16px;">
                  <el-button
                    :type="activeTab === 'received' ? 'primary' : 'default'"
                    @click="showReceived"
                  >接收的消息</el-button>
                  <el-button
                    :type="activeTab === 'sent' ? 'primary' : 'default'"
                    @click="showSent"
                  >发送的消息</el-button>
                </div>

                <div class="notice-box">
                  <!-- 消息列表部分 -->
                  <el-scrollbar class="inbox-list" :style="{ width: isDetailOpen ? '30%' : '100%' }">
                      <el-card
                          v-for="item in notices"
                          :key="item.id"
                          class="notice-item"
                          @click="openNoticeDetail(item.id, item)"
                      >
                          <div class="notice-meta">
                            <span v-if="!item.isViewed" class="unread-dot"></span>
                              <span class="title">{{ item.title }}</span>
                              <span class="sender">
                                <template v-if="activeTab==='received'">来自：{{ item.senderName }}</template>
                                <template v-else>发送给：{{ item.receiverName }}</template>
                              </span>
                          </div>
                          <div class="notice-time">
                              <span>创建：{{ item.createTime }}</span>
                              <span>更新：{{ item.updateTime }}</span>
                          </div>
                      </el-card>

                      <div v-if="notices.length === 0" class="empty-state">暂无消息</div>
                  </el-scrollbar>

                  <!-- 消息详情部分 -->
                  <div v-if="isDetailOpen" class="notice-detail">
                      <div class="detail-header">
                          <el-button @click="closeDetail" type="text">收起消息</el-button>
                      </div>
                      <div class="detail-content">
                          <h3>{{ currentMessage.title }}</h3>
                          <p v-if="activeTab==='received'"><strong>发件人：</strong>{{ currentMessage.senderName }}</p>
                          <p v-else><strong>发件人：</strong>{{ myUserName }}</p>
                          <p v-if="activeTab==='received'"><strong>收件人：</strong>{{ myUserName }}</p>
                          <p v-else><strong>收件人：</strong>{{ currentMessage.receiverName }}</p>
                          <p v-if="activeTab==='received'"><strong>发件人邮箱：</strong>{{ currentMessage.senderEmail }}</p>
                          <p v-else><strong>收件人邮箱：</strong>{{ currentMessage.receiverEmail }}</p>
                          <p><strong>创建时间：</strong>{{ currentMessage.createTime }}</p>
                          <p><strong>内容：</strong>{{ currentMessage.content }}</p>
                      </div>
                  </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useCookies } from 'vue3-cookies'
import router from '@/router'

const { cookies } = useCookies()

// 消息列表与详情状态
const notices = ref([])
const currentMessage = ref({})
const isDetailOpen = ref(false)

const myUserName = ref('') 

// 当前标签：'received' | 'sent'
const activeTab = ref('received')

// 页面加载或切换时获取消息
async function fetchReceived() {
  try {
    const userId = cookies.get('cid')
    const res = await axios.get('/api/notice/received', { params: { userID: userId } })
    notices.value = res.data.code === 200 ? res.data.data : []
  } catch (err) {
    console.error('获取接收的消息失败', err)
    notices.value = []
  }
}

async function fetchSent() {
  try {
    const userId = cookies.get('cid')
    const res = await axios.get('/api/notice/sended', { params: { userID: userId } })
    notices.value = res.data.code === 200 ? res.data.data : []
  } catch (err) {
    console.error('获取发送的消息失败', err)
    notices.value = []
  }
}

function showReceived() {
  activeTab.value = 'received'
  isDetailOpen.value = false
  fetchReceived()
}
function showSent() {
  activeTab.value = 'sent'
  isDetailOpen.value = false
  fetchSent()
}

// 打开消息详情
async function openNoticeDetail(id, item) {
  try {
    const res = await axios.get('/api/notice/id', { params: { id } })
    if (res.data.code === 200) {
      currentMessage.value = res.data.data
      console.log(currentMessage.value)
      isDetailOpen.value = true
      if (activeTab.value === 'received') item.isViewed = true
    }
  } catch (err) {
    console.error('获取消息详情失败', err)
  }
}

function closeDetail() {
  isDetailOpen.value = false
}

// 跳转发送页面
function gotoSend() {
  router.push({ path: '/teacher/messageSend' })
}

// 初始化时加载接收消息
onMounted(() => {
  myUserName.value = cookies.get('cname')
  fetchReceived()
})
</script>

<style scoped>
.index {
  margin-top: 80px;
}

.inbox {
  display: flex;
  justify-content: center;
}

.button-box {
  width: 20%;
  margin-bottom: 30px;
  margin-left: auto;
}

.inbox-container {
  display: flex;
  width: 85%;
  flex-direction: column;
}

.toggle-box {
  /* 样式由内联设置，也可以在此配置 */
}

.inbox-list {
  transition: width 0.3s ease;
}

.notice-item {
  margin-bottom: 12px;
  cursor: pointer;
  transition: box-shadow 0.2s;
}

.unread-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #409EFF;
  border-radius: 50%;
  margin-right: 8px;
}

.title {
  font-weight: 500;
  margin-right: auto;
}

.sender {
  color: #909399;
  font-size: 14px;
}

.notice-time {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}

.empty-state {
  text-align: center;
  color: #C0C4CC;
  padding: 40px 0;
}

.detail-header {
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  margin-top: 20px;
}

.detail-content h3 {
  font-size: 24px;
  font-weight: bold;
}

.detail-content p {
  font-size: 16px;
  margin: 10px 0;
}

.notice-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.notice-meta {
  display: flex;
  align-items: center;
  font-size: 16px;
  margin-bottom: 6px;
}

.notice-detail {
  width: 65%;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  margin-left: 20px;
}

.notice-box {
    display: flex;
  flex-wrap: wrap;
  text-align: center;

}
</style>
